const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const Package = require('./Package');

// 定义Discussion模型
const Discussion = sequelize.define('Discussion', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  package_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: Package,
      key: 'id'
    },
    comment: '包ID（可选）'
  },
  user_name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '用户名'
  },
  title: {
    type: DataTypes.STRING(200),
    allowNull: true,
    comment: '讨论标题'
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
    comment: '讨论内容'
  },
  likes: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: '点赞数'
  },
  parent_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    defaultValue: null,
    comment: '父评论ID（用于回复）'
  }
}, {
  tableName: 'discussions',
  indexes: [
    { name: 'idx_package_id', fields: ['package_id'] }
  ]
});

// 建立关系
Package.hasMany(Discussion, {
  foreignKey: 'package_id',
  as: 'discussions'
});

Discussion.belongsTo(Package, {
  foreignKey: 'package_id',
  as: 'package'
});

// 自关联（回复功能）
Discussion.belongsTo(Discussion, {
  foreignKey: 'parent_id',
  as: 'parent'
});

Discussion.hasMany(Discussion, {
  foreignKey: 'parent_id',
  as: 'replies'
});

module.exports = Discussion;